package com.coordinate.servlets;

import java.util.logging.Logger;
import java.io.IOException;

import com.google.appengine.api.datastore.Blob;

import com.coordinate.servlets.VoiceMessage;
import com.coordinate.core.message.impl.CVoiceMessage;
import com.coordinate.db.*;
import com.devicemantra.coordinate.ds.tests.PMF;

import javax.servlet.http.*;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;


import org.apache.commons.io.IOUtils;

@SuppressWarnings("serial")
public class GetVmMessage extends HttpServlet 
{
	private static final Logger log = Logger.getLogger(GetVmMessage.class.getName());
	  
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException 
	{
		
			boolean lDoesExist = true;
			CVoiceMessage lVm = null;
			String lVmKey = req.getParameter("vm_key");
			System.out.println("Request for Vm with key " + lVmKey);
			log.info("Enterinmg GetVmMessage with" + lVmKey);
			PersistenceManager pm = PMF.get().getPersistenceManager();
			try
			{
				lVm = pm.getObjectById(CVoiceMessage.class,lVmKey);
				lVm = pm.detachCopy(lVm);
				System.out.println("Found Object with with key " + lVmKey);
				log.info("Found Object with with key " + lVmKey);
			} catch(JDOObjectNotFoundException e)
			{
				lDoesExist = false;
				
			}
			pm.close();
			
			if(lDoesExist)
			{
				log.info("[ FOUND ]" + lVmKey);
				System.out.println("[ FOUND ]" + lVmKey);
				
			}
			else
			{
				log.warning("[ NOT FOUND ]" + lVmKey);
				System.out.println("[ NOT FOUND ]");
			}
			
			
			if( lDoesExist && (lVm != null) )
			{
				resp.setContentType(lVm.getContentType());
				Blob lBlob = lVm.getVm();
				resp.getOutputStream().write(lBlob.getBytes());
			}
		
		   log.info("Leaving GetVmMessage with: " + lVmKey);	
	       //resp.getOutputStream().flush();	
	       resp.getOutputStream().close();	
	 }
	
}
